﻿using Microsoft.Extensions.DependencyModel;
using SeckillService.Model;
using SeckillService.Repositorys;
using SeckillService.Services.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace SeckillService.Services
{
    /// <summary>
    /// 商品service实现
    /// </summary>
    [Dependency(ServiceLifetime.Transient)]
    public class SeckillService : CrudAppService<Seckill, SeckillDto, Guid>, ISeckillService
    {
        private ISeckillRepository seckillRepository;
        public SeckillService(ISeckillRepository repository) : base(repository)
        {
            seckillRepository = repository;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="SeckillProductId"></param>
        /// <returns></returns>
        public async Task<SeckillProductDto> GetSeckillProductAsync(Guid SeckillProductId)
        {
            var dto = await seckillRepository.GetSeckillProductAsync(SeckillProductId);
            return ObjectMapper.Map<SeckillProduct, SeckillProductDto>(dto);
        }

        /// <summary>
        /// 查询时间编号下商品列表
        /// </summary>
        /// <param name="SeckillId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<SeckillProductDto>> GetSeckillProductsAsync(Guid SeckillId)
        {
            var dtos = await seckillRepository.GetSeckillProductsAsync(SeckillId);
            return ObjectMapper.Map<List<SeckillProduct>, List<SeckillProductDto>>(dtos);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public override async Task<SeckillDto> UpdateAsync(Guid id, SeckillDto input)
        {
            var data = await seckillRepository.GetAsync(id);
            ObjectMapper.Map(input, data);
            Seckill sec = await seckillRepository.UpdateAsync(data);
            return ObjectMapper.Map<Seckill, SeckillDto>(sec);
        }

        /// <summary>
        /// 修改库存
        /// </summary>
        /// <param name="updateSeckillProductStockDto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task UpdateSeckillProductStockAsync(UpdateSeckillProductStockDto updateSeckillProductStockDto)
        {
            // 1、获取秒杀商品。根据商品Id。
            SeckillProduct seckillProduct = await seckillRepository.GetSeckillProductByProductIdAsync(updateSeckillProductStockDto.SeckillProductId);
            // 2、扣减秒杀库存
            seckillProduct.SeckillStock = seckillProduct.SeckillStock - updateSeckillProductStockDto.ProductCount;
            // 3、更新商品库存
            await seckillRepository.UpdateSeckillProductStockAsync(seckillProduct);
        }
    }
}
